package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.service.IOrderDetailService;
import com.hjj.springboot.service.IOrderService;
import com.hjj.springboot.service.IOrderTipsService;
import com.hjj.springboot.service.IRiderService;
import com.hjj.springboot.util.AddressUtil;
import com.hjj.springboot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IOrderTipsService orderTipsService;

    @Autowired
    private IRiderService riderService;

    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderNo",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<Order> orderList=orderService.list(map);
        for (Order order : orderList){
            order.setRider(riderService.getById(order.getRiderId()));
        }
        Long total=orderService.getTotal(map);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderList",orderList);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }

    @SystemLogs(operation = "订单状态",type = LogType.UPDATE)
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestBody Order order) {
        Order resultOrder = orderService.getById(order.getId());
        resultOrder.setStatus(order.getStatus());
        orderService.saveOrUpdate(resultOrder);
        return R.ok();
    }

    @SystemLogs(operation = "订单信息",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id) {
        Order order = orderService.getById(id);
        orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mId",id));
        orderTipsService.remove(new QueryWrapper<OrderTips>().eq("orderNo",order.getOrderNo()));
        orderService.removeById(id);
        return R.ok();
    }

    //    批量删除
    @SystemLogs(operation = "订单信息",type = LogType.BATCH_DELETE)
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        List<Order> orderList=orderService.list(new QueryWrapper<Order>().in("id",ids));
        orderService.removeByIds(ids);
        orderDetailService.remove(new QueryWrapper<OrderDetail>().in("mId",ids));
        orderTipsService.remove(new QueryWrapper<OrderTips>().in("orderNo",orderList.stream().map(Order::getOrderNo).collect(Collectors.toList())));
        return R.ok();
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("订单信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().like(StringUtil.isNotEmpty(queryStr),"orderNo",query));
        EasyExcel.write(response.getOutputStream(),Order.class)
                .sheet("订单信息")
                .doWrite(orderList);
    }

//    折线图数据
    @RequestMapping("/lineCharts")
    public R lineCharts() {
        List<Order> orderList=orderService.list();
        // 移除状态为1的订单
        orderList.removeIf(order -> order.getStatus() == 1);

        // 创建ZoneId对象以重用
        ZoneId zoneId = ZoneId.systemDefault();

        // 使用Map来同时存储每个日期的订单价格总和和订单数量
        Map<LocalDate, BigDecimal> dateToSumMap = new TreeMap<>();
        Map<LocalDate, Integer> dateToCountMap = new TreeMap<>();

        orderList.forEach(order -> {
            LocalDate date = order.getPayDate().toInstant().atZone(zoneId).toLocalDate();
            dateToSumMap.merge(date, order.getTotalPrice(), BigDecimal::add); //当前日期总收入
            dateToCountMap.merge(date, 1, Integer::sum); //当前日期总销售量
        });

        List<LocalDate> dates = new ArrayList<>(dateToSumMap.keySet());
        List<BigDecimal> prices = dates.stream().map(dateToSumMap::get).collect(Collectors.toList());
        List<Integer> counts = dates.stream().map(dateToCountMap::get).collect(Collectors.toList());

        Map<String,Object> map=new HashMap<>();
        map.put("dates",dates);
        map.put("prices",prices);
        map.put("counts",counts);
        return R.ok(map);
    }

//    地图数据
    @RequestMapping("/mapCharts")
    public R mapCharts() {
        List<Order> orderList=orderService.list();
        // 移除状态为1的订单
        orderList.removeIf(order -> order.getStatus() == 1);
        // 根据地址中的省份进行分组，并计算每个省份的订单数量
        Map<String, Long> provinceOrderCounts = orderList.stream()
                .collect(Collectors.groupingBy(order -> AddressUtil.extractProvince(order.getAddress()), Collectors.counting()));

        // 将分组后的省份和订单数量转换为指定格式的列表
        List<Map<String, Object>> provinceDataList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : provinceOrderCounts.entrySet()) {
            Map<String, Object> provinceData = new HashMap<>();
            provinceData.put("name", entry.getKey()); // 省份名称
            provinceData.put("value", entry.getValue()); // 相同省份数量
            provinceDataList.add(provinceData);
        }

        // 使用Stream API找到最大的订单数量
        long maxCount = provinceOrderCounts.values().stream()
                .max(Comparator.naturalOrder())
                .orElse(0L); // 如果没有值，则默认为0

        // 创建一个Map来存放地图数据
        Map<String, Object> map = new HashMap<>();
        // 将转换后的省份数据列表放入Map中
        map.put("provinceData", provinceDataList);
        // 将最大订单数量加入到map中
        map.put("maxCount", maxCount);
        return R.ok(map);
    }

    @RequestMapping("/orderNum")
    public R orderNum() {
        int num=orderService.count(new QueryWrapper<Order>().ne("status",1));
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderNum",num);
        return R.ok(map);
    }

    @RequestMapping("/orderPay")
    public R orderPay() {
        List<Order> orderList=orderService.list();
        orderList.removeIf(order -> order.getStatus()==1);
        BigDecimal totalPrice = orderList.stream().map(Order::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String,Object> map=new HashMap<>();
        map.put("orderPay",totalPrice);
        return R.ok(map);
    }

}
